import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:get/get.dart';
import 'package:largefriends/config/lf_im_type.dart';
import 'package:largefriends/entity/entities/lf_user_entity.dart';
import 'package:largefriends/net/lf_api_util.dart';
import 'package:largefriends/pages/lf_base_controller.dart';
import 'package:largefriends/pages/lf_chat_detail/lf_chat_detail_logic.dart';
import 'package:largefriends/pages/lf_tab_message/lf_message_empty.dart';
import 'package:largefriends/res/lf_color.dart';
import 'package:largefriends/res/lf_double_ext.dart';
import 'package:largefriends/res/lf_fonts.dart';
import 'package:largefriends/res/lf_int_ext.dart';
import 'package:largefriends/res/lf_string_ext.dart';
import 'package:largefriends/res/lf_text_style.dart';
import 'package:largefriends/service/lf_auth_service.dart';
import 'package:largefriends/utils/lf_date_time_extension.dart';
import 'package:largefriends/utils/lf_scroll_behavior.dart';
import 'package:largefriends/widgets/common_failed_page.dart';
import 'package:largefriends/widgets/dialog_action_tip.dart';
import 'package:uuid/uuid.dart';

import '../../res.dart';
import '../../res/lf_widget_ext.dart';
import '../../res/strings/lf_strings.dart';
import '../../widgets/custom_cache_image.dart';
import 'lf_message_loading.dart';
import 'lf_tab_message_logic.dart';

class LfTabMessagePage extends StatefulWidget {
  const LfTabMessagePage({super.key});

  @override
  State<LfTabMessagePage> createState() => _LfTabMessagePageState();
}

class _LfTabMessagePageState extends State<LfTabMessagePage> {
  final logic = Get.put(LfTabMessageLogic());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: ShaderMask(
            shaderCallback: (Rect bounds) {
              return LinearGradient(
                begin: const Alignment(-0.5, -0.9),
                end: const Alignment(0.5, 0.9),
                colors: [colorFF007F, colorFF007F, colorBF00FF, colorBF00FF],
              ).createShader(Offset.zero & bounds.size);
            },
            blendMode: BlendMode.srcATop,
            child: Text(
              'Messages',
              style: TextStyle(
                  fontSize: 28.sp,
                  fontFamily: fontYoungSerif,
                  letterSpacing: 1.2),
            )),
      ),
      body: GetBuilder<LfTabMessageLogic>(
        builder: (logic) {
          if (logic.dataList.isEmpty) {
            if (logic.state == LoadingState.init ||
                logic.state == LoadingState.loading) {
              return const LfMessageLoading();
            } else if (logic.state == LoadingState.failed) {
              return CommonFailedPage(
                retry: () {
                  logic.getCustomParamHttpRequest(isRefresh: true);
                },
              );
            }
            return const LfMessageEmpty();
          }
          return Stack(
            children: [
              Positioned.fill(
                child: ScrollConfiguration(
                  behavior: LfScrollBehavior(),
                  child: SlidableAutoCloseBehavior(
                    closeWhenOpened: true,
                    closeWhenTapped: true,
                    child: EasyRefresh(
                      controller: logic.refreshController,
                      onLoad: () async {
                        var result = await logic.getCustomParamHttpRequest(
                            isRefresh: false);
                        return result;
                      },
                      onRefresh: () async {
                        var result = await logic.getCustomParamHttpRequest(
                            isRefresh: true);
                        return result;
                      },
                      child: CustomScrollView(
                        slivers: [
                          SliverList.separated(
                            itemBuilder: (context, index) {
                              return _buildItem(logic.dataList[index]);
                            },
                            separatorBuilder: (context, index) {
                              return Container(
                                height: 0.8.h,
                                color: color514F62.withAlpha(26),
                                margin: EdgeInsets.symmetric(horizontal: 15.w),
                              );
                            },
                            itemCount: logic.dataList.length,
                          ),
                          Obx(() =>
                              logic.authService.bottomNotification.value !=
                                      BottomNotificationType.none
                                  ? 30.h.sbh
                                  : empty).sliverBox,
                        ],
                      ),
                    ),
                  ),
                ),
              ),
              Align(
                alignment: Alignment.bottomCenter,
                child: Obx(() {
                  if (logic.authService.bottomNotification.value !=
                      BottomNotificationType.none) {
                    return 1.h.sbh;

                    ///TODO
                    // return getBottomTipWidget(
                    //     logic.authService.bottomNotification.value);
                  } else {
                    return 1.h.sbh;
                  }
                }),
              )
            ],
          );
        },
      ),
    );
  }

  Widget _buildItem(LfUserEntity chatUserEntity) {
    return Slidable(
        key: Key(chatUserEntity.userId ?? const Uuid().toString()),
        endActionPane: ActionPane(
          motion: const ScrollMotion(),
          dragDismissible: false,
          children: [
            SlidableAction(
              flex: 1,
              onPressed: (context) async {
                await showActionTips(
                  tips: strDeleteConversationTip.tr,
                  actionButtonTip: strSure.tr,
                  action: () async {
                    deleteConversation(uid: chatUserEntity.userId!);
                  },
                );
              },
              backgroundColor: color514F62,
              foregroundColor: colorFEFEFE,
              icon: Icons.delete,
              label: strDelete.tr,
            )
          ],
        ),
        child: _userWidget(chatUserEntity));
  }

  _userWidget(LfUserEntity chatUserEntity) {
    bool isSupport = chatUserEntity.isSupport();
    bool isBlockedMe = chatUserEntity.isBlockMe();
    bool isHidden = chatUserEntity.isHiddenForMe();
    bool isEnable = chatUserEntity.isEnable();
    bool canShowProfile = !isBlockedMe && !isHidden && isEnable;
    return InkWell(
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 10.h, horizontal: 15.w),
        child: Row(
          children: [
            CustomCacheImage(
              imageUrl: isSupport
                  ? ""
                  : canShowProfile
                      ? chatUserEntity.avatar
                      : "",
              width: 50.r,
              height: 50.r,
              isCircle: true,
            ),
            10.w.sbw,
            Expanded(
                child: Column(
              children: [
                Row(
                  children: [
                    Expanded(
                        child: Row(
                      children: [
                        Flexible(
                            child: Text(
                          chatUserEntity.username.toUpperCase(),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          textWidthBasis: TextWidthBasis.longestLine,
                          style: lfTextStyle(
                              fontFamily: fontMedium,
                              sp: 16.sp,
                              color: (!isEnable || isBlockedMe)
                                  ? colorFEFEFE
                                  : colorFEFEFE),
                        )),
                        chatUserEntity.isVerified()
                            ? Padding(
                                padding: EdgeInsets.only(left: 5.w),
                                child: Image.asset(
                                  Res.ic_verified,
                                  width: 16.r,
                                  color: Colors.blueAccent,
                                ),
                              )
                            : empty,
                        chatUserEntity.isGold()
                            ? Padding(
                                padding: EdgeInsets.only(left: 5.w),
                                child: Image.asset(
                                  Res.icon_premium,
                                  width: 18.r,
                                  color: colorFF007F,
                                ),
                              )
                            : empty,
                        chatUserEntity.isOnline()
                            ? Padding(
                                padding: EdgeInsets.only(left: 5.w),
                                child: Container(
                                  decoration: const BoxDecoration(
                                      color: Colors.lightGreen,
                                      shape: BoxShape.circle),
                                  width: 10.r,
                                  height: 10.r,
                                ),
                              )
                            : chatUserEntity.isOnlineRecently()
                                ? Padding(
                                    padding: EdgeInsets.only(left: 5.w),
                                    child: Container(
                                      decoration: BoxDecoration(
                                          border: Border.all(
                                              color: Colors.lightGreen,
                                              width: 2.r),
                                          shape: BoxShape.circle),
                                      width: 10.r,
                                      height: 10.r,
                                    ),
                                  )
                                : empty,
                      ],
                    )),
                    20.w.sbw,
                    Text(
                      DateTime.fromMillisecondsSinceEpoch(
                              parseInt(chatUserEntity.created) * 1000)
                          .getConversationTimeString(),
                      style: lfTextStyle(
                        fontFamily: fontRegular,
                        sp: 13.sp,
                      ),
                    )
                  ],
                ),
                Row(
                  children: [
                    Expanded(
                        child: Text(
                      _getLastMessageContent(chatUserEntity),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: lfTextStyle(
                        sp: 15.sp,
                        fontFamily: fontRegular,
                        color: chatUserEntity.newNumber > 0? colorFEFEFE:color514F62
                      ),
                    )),
                    // Container()
                    10.w.sbw,
                    Badge.count(
                        textStyle:
                            TextStyle(fontSize: 12.sp, color: Colors.white),
                        backgroundColor: colorFF007F,
                        count: chatUserEntity.newNumber,
                        isLabelVisible: chatUserEntity.newNumber > 0)
                  ],
                )
              ],
            ))
          ],
        ),
      ),
      onTap: () {
        toChatPage(uid: chatUserEntity.userId!, userEntity: chatUserEntity);
      },
      onLongPress: () {
        showActionTips(
          tips: strDeleteConversationTip.tr,
          actionButtonTip: strSure.tr,
          action: () async {
            deleteConversation(uid: chatUserEntity.userId!);
          },
        );
      },
    );
  }

  ///显示最后一条消息的文本内容
  String _getLastMessageContent(LfUserEntity chatUserEntity) {
    var messageType = IMMessageType.values.firstWhere(
        (element) => element.value == chatUserEntity.messageType,
        orElse: () => IMMessageType.messageTypeUnknow);
    String tips;
    switch (messageType) {
      case IMMessageType.text:
      case IMMessageType.reply:
      case IMMessageType.autoReply:
      case IMMessageType.supportText:
      case IMMessageType.messageTypeRequestUploadPhoto:
        tips = chatUserEntity.lastMessage;
        break;
      case IMMessageType.image:
        tips = '[IMAGE]';
        break;
      case IMMessageType.stickerIcon:
        tips = '[STICKER]';
        break;
      case IMMessageType.stickerAnim:
        tips = '[STICKER]';
        break;
      case IMMessageType.customSticker:
        tips = '[IMAGE]';
        break;
      case IMMessageType.wink:
        tips = '[WINK]';
        break;
      case IMMessageType.voice:
        tips = '[AUDIO]';
        break;
      case IMMessageType.privateAlbumRequest:
      case IMMessageType.acceptPrivateAlbumRequest:
        tips = '[PRIVATE PHOTOS]';
        break;
      case IMMessageType.match:
        tips = "It's a Match";
        break;
      case IMMessageType.themeChange:
      case IMMessageType.themeClear:
        tips = '[THEME]';
        break;
      case IMMessageType.messageTypeRecall:
        if (chatUserEntity.lastMessageSenderId ==
            logic.authService.currentAccount?.userId) {
          tips = strYouUnsentMessage.tr;
        } else {
          tips = '${chatUserEntity.username.toUpperCase()} unsent a message.';
        }
        break;
      case IMMessageType.likeCompanion:
      case IMMessageType.joinCompanion:
      case IMMessageType.rehostCompanion:
      case IMMessageType.inviteCompanion:
        tips = '[EVENT]';
        break;
      case IMMessageType.premiumWink:
        tips = '[${strWink.tr}]';
        break;
      // case IMMessageType.messageTypeRequestUploadPhoto:
      //   tips = '[UPLOAD PHOTOS]';
      //   break;
      default:
        if (chatUserEntity.lastMessageSenderId ==
            logic.authService.currentAccount?.userId) {
          tips = strUnsupportedMessage.tr;
        } else {
          tips = strNewMessage.tr;
        }
    }
    var isSelf = chatUserEntity.lastMessageSenderId ==
        logic.authService.currentAccount?.userId;
    return tips
        .replaceAll(RegExp(r'\s{2,}'), ' ')
        .replaceAll('&lt;br&gt;', '')
        .replaceAll(RegExp(r'(\?m)^\s*\$(\n|\r\n)'), ' ')
        .replaceAll('\n', ' ')
        .replaceWord(isSelf);
  }
}
